package com.wan.servlet.bill;

import com.alibaba.fastjson.JSONArray;
import com.wan.pojo.Bill;
import com.wan.pojo.Provider;
import com.wan.pojo.User;
import com.wan.service.Provider.ProviderServiceImpl;
import com.wan.service.bill.BillServiceImpl;
import com.wan.util.Constants;
import com.wan.util.PageSupport;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.Date;

public class BillServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query")) {
            this.queryBill(req,resp);
        }else if (method.equals("add")) {
            this.addBill(req,resp);
        }else if (method.equals("getproviderlist")) {
            this.getProviderList(req,resp);
        }else if (method.equals("delbill")) {
            this.deleteBill(req,resp);
        }else if (method.equals("modify")) {
            this.dispatcherModifyPage(req,resp);
        }else if (method.equals("modifysave")) {
            this.updateBill(req,resp);
        }else if (method.equals("view")) {
            this.dispatcherViewPage(req,resp);
        }

    }
    // 携带用户，跳转到view界面
    public void dispatcherViewPage (HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("billid");

        BillServiceImpl billService = new BillServiceImpl();
        Bill bill = billService.getBillById(Integer.valueOf(id));

        if (bill != null) {
            req.setAttribute("bill",bill);
            try {
                req.getRequestDispatcher("/jsp/billview.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 修改用户的信息
    public void updateBill (HttpServletRequest req, HttpServletResponse resp) {
        // 收集前端填写的信息
        String id = req.getParameter("id");
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        // 将信息封装到一个对象中去
        Bill bill = new Bill();
        bill.setId(Integer.valueOf(id));
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductUnit(productUnit);
        bill.setProductCount(BigDecimal.valueOf(Double.valueOf(productCount)));
        bill.setTotalPrice(BigDecimal.valueOf(Double.valueOf(totalPrice)));
        bill.setProviderId(Integer.valueOf(providerId));
        bill.setIsPayment(Integer.valueOf(isPayment));
        bill.setModifyDate(new Date(System.currentTimeMillis()));

        BillServiceImpl billService = new BillServiceImpl();
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        int impactedCount = billService.updateBill(bill,user.getId());
        if (impactedCount > 0) {
            try {
                resp.sendRedirect("/jsp/bill.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                req.getRequestDispatcher("/jsp/billmodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 跳转到修改页面，需要携带这个对象
    public void dispatcherModifyPage (HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("billid");
        BillServiceImpl billService = new BillServiceImpl();
        Bill bill = billService.getBillById(Integer.valueOf(id));
        if (bill != null) {
            req.setAttribute("bill",bill);
            try {
                req.getRequestDispatcher("/jsp/billmodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 删除一个订单,ajax 传递过来一个id，通过这个id删除
    public void deleteBill (HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("billid");
        BillServiceImpl billService = new BillServiceImpl();
        int impactedCount = 0;
        if (id != null) {
            impactedCount = billService.deleteBill(Integer.valueOf(id));
        }
        // 用map把返回信息存储起来，方便后续转换成json的格式
        Map<String, String> resultMap = new HashMap<String,String>();
        if (id == null){
            resultMap.put("delResult","notexist");
        } else {
            // 如果受影响的行数大于0，那么表示删除成功
            if (impactedCount > 0) {
                resultMap.put("delResult","true");
            }else if (impactedCount == 0) {
                resultMap.put("delResult","false");
            }
        }
        try {
            // 要返回json格式
            resp.setContentType("application/json");
            // 得到流
            PrintWriter writer = resp.getWriter();
            // 以json的格式写出
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // ajax，返回供应商列表，以json的格式返回
    public void getProviderList (HttpServletRequest req, HttpServletResponse resp) {
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        List<Provider> providerList_ = providerService.getProviderList_();
        try {
            // 要返回json格式
            resp.setContentType("application/json");
            // 得到流
            PrintWriter writer = resp.getWriter();
            // 以json的格式写出
            writer.write(JSONArray.toJSONString(providerList_));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 增加一个订单
    public void addBill (HttpServletRequest req, HttpServletResponse resp) {
        // 从前端获取填写的所有参数
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        // 将参数封装到一个对象中
        Bill bill = new Bill();
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductUnit(productUnit);
        bill.setProductCount(BigDecimal.valueOf(Long.valueOf(productCount)));
        bill.setTotalPrice(BigDecimal.valueOf(Long.valueOf(totalPrice)));
        bill.setProviderId(Integer.valueOf(providerId));
        bill.setIsPayment(Integer.valueOf(isPayment));
        try {
            bill.setCreationDate(new java.sql.Date(System.currentTimeMillis()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 持久化到数据库中去
        BillServiceImpl billService = new BillServiceImpl();
        User user = (User)req.getSession().getAttribute(Constants.USER_SESSION);
        int impactedCount = billService.insertBill(bill,user.getId());

        if (impactedCount > 0) {
            try {
                resp.sendRedirect("/jsp/bill.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                req.getRequestDispatcher("/jsp/billadd.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 查询所有的订单
    public void queryBill (HttpServletRequest req, HttpServletResponse resp) {
        // 从前端获取参数
        String queryProductName = req.getParameter("queryProductName");
        String queryProviderId = req.getParameter("queryProviderId");
        String queryIsPayment = req.getParameter("queryIsPayment");
        String pageIndex = req.getParameter("pageIndex");


        // 准备获取用户列表
        BillServiceImpl billService = new BillServiceImpl();
        ArrayList<Bill> billArrayList = null;
        // 第一次走这个请求，一定是第一页，页面大小是固定的
        // 这个大小可以写到配置文件中，那样更容易更改，在这写的固定了就不好改
        int pageSize = 5;
        int currentPageNum = 1;

        if (queryProductName == "") {
            queryProductName = null;
        }
        // 对整数进行处理
        if (queryProviderId == "") {
            queryProviderId = null;
        }
        int queryProviderId_int = 0;
        if (queryProviderId != null) {
            queryProviderId_int = Integer.valueOf(queryProviderId);
        }
        // 对整数进行处理
        if (queryIsPayment == "") {
            queryIsPayment = null;
        }
        // 对整数进行处理
        int queryIsPayment_int = 0;
        if (queryIsPayment != null) {
            queryIsPayment_int = Integer.valueOf(queryIsPayment);
        }
        if (pageIndex != null) {
            currentPageNum = Integer.parseInt(pageIndex);//解析出来的值就是1，这是默认情况下的东西
        }

        // 获取订单的总数(分页，上一页，下一页，首页，尾页)
        int totalCount = billService.getBillCount(queryProductName, queryProviderId_int,queryIsPayment_int);
        PageSupport pageSupport = new PageSupport(); // 总页数支持
        pageSupport.setCurrentPageNo(currentPageNum);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        // 算出一共应该有多少页
        int totalPageCount = pageSupport.getTotalPageCount();

        // 控制首页和尾页
        // 如果页面要小于1，就显示第一页
        if (totalPageCount < 1) {
            currentPageNum = 1;
        }else if (currentPageNum > totalPageCount) {
            currentPageNum = totalPageCount;
        }

        // 获取订单列表展示 中间的一大堆都是为了执行这个代码，获得用户列表
        // 为了sql的正常运行，不能让任何一个数据的问题使得sql不能运行
        billArrayList = (ArrayList<Bill>) billService.getBillList(queryProductName,queryProviderId_int,queryIsPayment_int,currentPageNum,pageSize);
        // 将拿到的订单列表
        req.setAttribute("billList",billArrayList);

        // 拿到供应商列表
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        List<Provider> providerList = providerService.getProviderList_();
        req.setAttribute("providerList",providerList);

        // 返回页数，分页的相关支持
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNum);
        req.setAttribute("queryProductName",queryProductName);
        req.setAttribute("queryProviderId",queryProviderId);
        // 携带参数，返回前端看看
        try {
            req.getRequestDispatcher("/jsp/billlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
